package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.handler.WorkException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.mapper.UserInfoMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.service.UserInfoService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserService systemUserService;









    /**
     * 获取验证码
     *
     * @return
     */
    @Override
    public CaptchaVo getCaptcha() {
        //1、实例化验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);// 宽，高，位数
        // 2、获取验证码文本内容并设置为小写
        String verCode = specCaptcha.text().toLowerCase();
        //3、设置redis的key，保证唯一性
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();//这一步需要提前封装好常量类
        // 4、将验证码对象转为base64格式
        String image = specCaptcha.toBase64();
        // 5、存入redis并设置过期时间为1分钟
        stringRedisTemplate.opsForValue().set(key, verCode, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        // 6、将key和base64返回给前端
        return new CaptchaVo(image, key);
    }

    /**
     * 登录方法
     * @param loginVo
     * @return
     *
     * 本方法还有点繁琐，还可以进一步优化
     */
    @Override
    public String login(LoginVo loginVo) {
        /*
        1、先校验所有前端传递过来的参数，把好自己的校验关
        2、比对前端传递的参数信息和数据库中的信息
        3、如果比对成功，则生成一个token返回给前端
        4、如果比对失败，则返回错误信息
        5、生成token的逻辑，可以使用jwt工具类来完成，需要你封装一个工具类来完成，包含生成token和解析token的方法
         */
        //校验用户名是否为空
        if (!StringUtils.hasText(loginVo.getUsername())) {
            throw new WorkException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //校验密码是否为空
        if (!StringUtils.hasText(loginVo.getPassword())) {
            throw new WorkException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //校验验证码是否为空
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new WorkException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        SystemUser userInfo = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, loginVo.getUsername()));

        //判断用户是否存在
        if (userInfo == null) {
            throw new WorkException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //判断用户名是否正确
        if (!userInfo.getUsername().equals(loginVo.getUsername())) {
            throw new WorkException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断密码是否正确
        if (!userInfo.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new WorkException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断账号状态是否可用
        if ((userInfo.getStatus()) == BaseStatus.DISABLE) {
            throw new WorkException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //校验验证码是否过期顺便验证验证码是否正确
        if (stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey()) == null) {
            throw new WorkException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }else if (!stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey()).equals(loginVo.getCaptchaCode())) {
            throw new WorkException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        String token = JwtUtil.createJWT(userInfo.getId(), userInfo.getName());

        //生成token返回给前端

        return token;
    }
}
